package com.nexgo.payment.action.confirmtransdetail;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.TransUtils;
import com.nexgo.payment.widget.ItemLinearLayout;
import com.nexgo.payment.widget.TitleBuilder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import java8.util.Optional;

/**
 * 显示交易详情界面
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月25日
 */
public class ConfirmTransDetailFragment extends BaseFragment implements Action<ActionStep>, ConfirmTransDetailContract.View, BaseFragment.DownTimerListener {
    private static final String TRANS_NUM = "transNum";

    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.item_card_no)
    ItemLinearLayout itemCardNo;
    @BindView(R.id.item_pay_code_no)
    ItemLinearLayout itemPayCodeNo;
    @BindView(R.id.item_pay_trace_code)
    ItemLinearLayout itemPaceTraceCode;
    @BindView(R.id.item_date_time)
    ItemLinearLayout itemTradeTime;
    @BindView(R.id.item_trade_type)
    ItemLinearLayout itemTradeType;
    @BindView(R.id.item_merchant_no)
    ItemLinearLayout itemMerchantNo;
    @BindView(R.id.item_terminal_no)
    ItemLinearLayout itemTerminalNo;
    @BindView(R.id.item_auth_code)
    ItemLinearLayout itemAuthCode;
    @BindView(R.id.item_refer_no)
    ItemLinearLayout itemReferNo;
    @BindView(R.id.item_batch_no)
    ItemLinearLayout itemBatchNo;
    @BindView(R.id.item_trace_num)
    ItemLinearLayout itemTraceNum;
    @BindView(R.id.item_op_no)
    ItemLinearLayout itemOpNo;
    @BindView(R.id.title_tv_right)
    TextView tvTitleRight;
    Unbinder unbinder;

    private OnActionListener mListener;
    private ConfirmTransDetailContract.Presenter mPresenter;

    public ConfirmTransDetailFragment() {
        // Required empty public constructor
    }

    public static ConfirmTransDetailFragment newInstance(String traceNum) {
        ConfirmTransDetailFragment fragment = new ConfirmTransDetailFragment();
        Bundle args = new Bundle();
        args.putString(TRANS_NUM, traceNum);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String traceNum = null;
        if (getArguments() != null) {
            traceNum = getArguments().getString(TRANS_NUM,"");
        }
        new ConfirmTransDetailPresenter(this, Repository.getInstance(), traceNum);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_confirm_trans_detail, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    //初始化标题栏
    private void initTitle(View view) {
        new TitleBuilder(view)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(R.string.trans_detail_title))
                .build();
    }

    @Override
    protected void initEvent() {}

    @Override
    protected void initData() {}

    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter != null){
            mPresenter.start();
        }
    }

    @OnClick({R.id.title_iv_left, R.id.btn_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_iv_left:
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, null));
                }
                break;
            case R.id.btn_confirm:
                mPresenter.confirmDetail();
                break;
            default:
                break;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.CONFIRM_TRANS_DETAIL;
    }

    @Override
    public void setPresenter(ConfirmTransDetailContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showTransDetail(TransRecord transRecord) {
        //交易金额
        tvAmount.setText(StringUtils.formatAmount(transRecord.getAmount(), SysConstant.FUND_DIGITS));
        //卡号
        Optional.ofNullable(transRecord.getPan())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    itemCardNo.setVisibility(View.VISIBLE);
                    itemCardNo.setRightText(TransUtils.maskPan(s));
                });
        //支付码号（扫码相关）
        Optional.ofNullable(transRecord.getPayCodeNo())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    itemPayCodeNo.setVisibility(View.VISIBLE);
                    itemPayCodeNo.setRightText(TransUtils.maskPan(s));
                });
        //付款凭证码（扫码相关）
        Optional.ofNullable(transRecord.getPayTraceCode())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    itemPaceTraceCode.setVisibility(View.VISIBLE);
                    itemPaceTraceCode.setRightText(s);
                });
        //交易时间
        itemTradeTime.setRightText(StringUtils.formatDateTime(transRecord.getDate(),transRecord.getTime()));
        //交易类型
        itemTradeType.setRightText(TransType.values()[transRecord.getTransType()].getName());
        //商户号
        itemMerchantNo.setRightText(transRecord.getMerchantId());
        //终端号
        itemTerminalNo.setRightText(transRecord.getTerminalId());
        //授权码
        Optional.ofNullable(transRecord.getAuthCode())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    itemAuthCode.setVisibility(View.VISIBLE);
                    itemAuthCode.setRightText(s);
                });
        //参考号
        itemReferNo.setRightText(transRecord.getRefNum());
        //批次号
        itemBatchNo.setRightText(transRecord.getBatchNum());
        //凭证号
        itemTraceNum.setRightText(transRecord.getTraceNum());
        //操作员号
        itemOpNo.setRightText(String.format(SysConstant.LOCALE, "%02d", transRecord.getOperator()));

        //启动倒计时
        setDownTimer(SysConstant.TIME_OUT_60, this);
    }

    @Override
    public void showConfirm(TransRecord transRecord) {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, transRecord));
        }
    }

    @Override
    public void showErrMsg(String message) {
        Optional.ofNullable(message)
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> ToastUtils.showToast(s));
    }

    @Override
    public void showEmptyTransRecord() {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, null));
        }
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDownTimer();
        unbinder.unbind();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(String.valueOf(secondsUntilFinished));
    }

    @Override
    public void onFinish() {
        if (isActive()) {
            tvTitleRight.setText("0");
        }
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, null));
        }
    }
}
